package com.fy56.platform.logistics.restful.api.controller.wx;

import com.alibaba.fastjson.JSON;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.common.ResultStatus;
import com.fy56.platform.logistics.model.MiniProgram;
import com.fy56.platform.logistics.model.Order;
import com.fy56.platform.logistics.model.Vip;
import com.fy56.platform.logistics.restful.api.app.authorization.annotation.Authorization;
import com.fy56.platform.logistics.restful.api.utils.StringToConversionUtil;
import com.fy56.platform.logistics.restful.api.utils.redis.RedisBusinessUtils;
import com.fy56.platform.logistics.restful.api.utils.weChat.WeChatAppletUtil;
import com.fy56.platform.logistics.restful.api.utils.weChat.WeChatEnum;
import com.fy56.platform.logistics.service.web.IMiniProgramService;
import com.fy56.platform.logistics.service.wx.IOrderService;
import com.fy56.platform.logistics.service.wx.IVipService;
import com.fy56.platform.logistics.utils.BeanTransitionShopUtil;
import com.fy56.platform.logistics.vo.OrderLogisticsNoticeVo;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

/**
 * [接口服务类]微信小程序-消息推送
 */
@Api(value = "WxMessagePush", description = "微信小程序-消息推送", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/wxMessagePush")
public class WxMessagePushController {
    @Autowired
    private IMiniProgramService iMiniProgramService;

    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private IVipService iVipService;

    @Autowired
    private RedisBusinessUtils redisBusinessUtils;

    /*----------------------------------------------------------------------------------------------------*/

    private static Logger log = Logger.getLogger(WxMessagePushController.class);

    /*----------------------------------------------------------------------------------------------------*/

    //订单物流通知<公版>
    @RequestMapping(value = "/orderLogisticsNotice/overt", method = { RequestMethod.POST })
    @ApiOperation(value = "推送-订单物流通知<公版>")
    @Authorization
    public ResultModel getOrderLogisticsNotice(@RequestParam String appId, @RequestParam Long orderId, @RequestParam String  noticeType) {
        //参数验证
//        Assert.notNull(appId, "appId不能为空");
//        Assert.notNull(orderId, "订单Id不能为空");
//        Assert.notNull(noticeType, "通知类型不能为空");
        if(!StringToConversionUtil.isNotNull(appId)){
            return ResultModel.error(ResultStatus.CLIENT_ERROR, "appId不能为空");
        }
        if(!StringToConversionUtil.isNotNull(orderId)){
            return ResultModel.error(ResultStatus.CLIENT_ERROR, "订单Id不能为空");
        }
        if(!StringToConversionUtil.isNotNull(noticeType)){
            return ResultModel.error(ResultStatus.CLIENT_ERROR, "通知类型不能为空");
        }

        try {
            MiniProgram miniProgram = iMiniProgramService.selectByAppId(appId);

            Order orderEntity = iOrderService.selectById(orderId);
            Vip vpiEntity = iVipService.selectVipOpenidByMobile(orderEntity.getVipNumber());

            // 获取微信小程序-accessToken
            String accessToken = redisBusinessUtils.getWxAppletAccessToken(appId, miniProgram.getSecret());

            OrderLogisticsNoticeVo modelVo = new OrderLogisticsNoticeVo();
            modelVo.setTemplateId("IqTvf02gHVuw4aos2HnmDVMtEsgYUcRXaLhmI99ZkbM");//订单物流通知-模板id<公版>
            modelVo.setPage("pages/order/orderDetail?order=" + BeanTransitionShopUtil.ots(orderEntity));
            modelVo.setReceiveCompany(orderEntity.getReceiveCompany());//承运物流名称
            modelVo.setNoticeTime(StringToConversionUtil.DateToString("yyyy/MM/dd HH:mm", orderEntity.getOrderCreateTime()));//通知时间
            modelVo.setOrderNumber(orderEntity.getOrderNumber());//运单号
            modelVo.setRemarks(orderEntity.getRemarks());//货物详情
            modelVo.setNoticeType(noticeType);//通知类型[1订单下单,2订单转正,3订单已发车,4订单已到达,5订单已完成]

            //[发送]微信小程序-订阅消息
//            Map<String, Object> retMap = WeChatAppletUtil.getSubscribeMessage(accessToken, vpiEntity.getOpenId(), modelVo.getTemplateId(), modelVo.getPage(),
//                    modelVo.getInputData(), null, null);
            Map<String, Object> retMap = WeChatAppletUtil.getSubscribeMessage(accessToken, vpiEntity.getOpenId(), modelVo.getTemplateId(), modelVo.getPage(),
                    modelVo.getInputData(), WeChatEnum.SubscribeMessage_MiniprogramState.DEVELOPER, null);

            if("0".equals(retMap.get("errcode").toString())){
                log.info("===>微信小程序-订阅消息_推送成功！");
                return ResultModel.ok();
            }else{
                String errStr = "===>微信小程序-订阅消息_推送失败！errcode:"+retMap.get("errcode").toString()+"\t"+retMap.get("errmsg").toString();
                log.info(errStr);
                return ResultModel.error(ResultStatus.SERVER_ERROR, errStr);
            }
        } catch (Exception e) {
            log.error("推送-订单物流通知失败",e);
            return ResultModel.error(ResultStatus.SERVER_ERROR, "推送-订单物流通知失败");
        } finally {
        }
    }

    //订单物流通知<定制版>
    @RequestMapping(value = "/orderLogisticsNotice/orient", method = { RequestMethod.POST })
    @ApiOperation(value = "推送-订单物流通知<定制版>")
    @Authorization
    public ResultModel getOrderLogisticsNotice2(@RequestParam String data) {
        //参数验证
        if (data == null || data.length() == 0) {
            return ResultModel.error(ResultStatus.CLIENT_ERROR, "缺少参数");
        }

        OrderLogisticsNoticeVo modelVo = null;
        try {
            //参数转型
            modelVo = JSON.parseObject(data).toJavaObject(OrderLogisticsNoticeVo.class);
            //参数验证
            if(!StringToConversionUtil.isNotNull(modelVo.getAppId())){
                return ResultModel.error(ResultStatus.SERVER_ERROR, "appId不能为空");
            }
            if(!StringToConversionUtil.isNotNull(modelVo.getVipNumber())){
                return ResultModel.error(ResultStatus.CLIENT_ERROR, "vip用户手机号不能为空");
            }
            if(!StringToConversionUtil.isNotNull(modelVo.getNoticeType())){
                return ResultModel.error(ResultStatus.CLIENT_ERROR, "通知类型不能为空");
            }
            if(!StringToConversionUtil.isNotNull(modelVo.getTemplateId())){
                //微信小程序-消息模板id, 默认:公版
                modelVo.setTemplateId("IqTvf02gHVuw4aos2HnmDVMtEsgYUcRXaLhmI99ZkbM");
            }
            if(!StringToConversionUtil.isNotNull(modelVo.getPage())){
                modelVo.setPage("pages/order/orderDetail?order=");//###########
            }else if("-1".equals(modelVo.getPage())){
                modelVo.setPage(null);
            }

            //[获取]微信小程序信息
            MiniProgram miniProgram = iMiniProgramService.selectByAppId(modelVo.getAppId());
//            //[获取]vip用户信息
//            Vip vpiEntity = iVipService.selectVipOpenidByMobile(modelVo.getVipNumber());

            // 获取微信小程序-accessToken
            String accessToken = redisBusinessUtils.getWxAppletAccessToken(modelVo.getAppId(), miniProgram.getSecret());

//            Map<String, Object> retMap = WeChatAppletUtil.getSubscribeMessage(accessToken, vpiEntity.getOpenId(), modelVo.getTemplateId(), modelVo.getPage(),
//                    modelVo.getInputData(), null, null);
            Map<String, Object> retMap = WeChatAppletUtil.getSubscribeMessage(accessToken, modelVo.getOpenId(), modelVo.getTemplateId(), modelVo.getPage(),
                    modelVo.getInputDataHuiLong(), WeChatEnum.SubscribeMessage_MiniprogramState.DEVELOPER, null);

            if("0".equals(retMap.get("errcode").toString())){
                log.info("===>微信小程序-订阅消息_推送成功！");
                return  ResultModel.ok();
            }else{
                String errStr = "===>微信小程序-订阅消息_推送失败！errcode:"+retMap.get("errcode").toString()+"\t"+retMap.get("errmsg").toString();
                log.info(errStr);
                return ResultModel.error(ResultStatus.SERVER_ERROR, errStr);
            }
        } catch (Exception e) {
            log.error("推送-订单物流通知失败", e);
            return ResultModel.error(ResultStatus.SERVER_ERROR, "推送-订单物流通知失败");
        } finally {
            modelVo = null;
        }
    }

    //订单物流通知<测试接口>
    @RequestMapping("/orderLogisticsNoticeTest")
    @ApiOperation(value = "推送-订单物流通知_测试接口")
    @Authorization
    public ResultModel getOrderLogisticsNoticeTest() {
        //临时写法
        String appId = "wx881c5f23c98d2b34";
        String appSecret = "0c0c3c26dc46a4c53ef45723f6a2f1d0";
        String openid = "oGFVJ5A5rhZlKuC8I0OI9EyrFHio";

        MiniProgram miniProgram = iMiniProgramService.selectByAppId(appId);

        //获取微信小程序-accessToken
        String accessToken = redisBusinessUtils.getWxAppletAccessToken(appId, appSecret);
//        String accessToken = "";
//        try {
//            // 获取微信小程序-accessToken
//            accessToken = WeChatAppletUtil.getAccessToken(appId, appSecret);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        OrderLogisticsNoticeVo modelVo = new OrderLogisticsNoticeVo();
        modelVo.setTemplateId("IqTvf02gHVuw4aos2HnmDVMtEsgYUcRXaLhmI99ZkbM");//订单物流通知-模板id<公版>
        modelVo.setPage("");
        modelVo.setReceiveCompany("fanyw物流");//承运物流名称
        modelVo.setNoticeTime(StringToConversionUtil.DateToString("yyyy/MM/dd HH:mm", new Date()));//通知时间
        modelVo.setOrderNumber("1145111000324324");//运单号
        modelVo.setRemarks("33332无奇不有寺");//货物详情
        modelVo.setNoticeType("1");//通知类型[1订单下单,2订单转正,3订单已发车,4订单已到达,5订单已完成]

        //[发送]微信小程序-订阅消息
        Map<String, Object> retMap = WeChatAppletUtil.getSubscribeMessage(accessToken, openid, modelVo.getTemplateId(), modelVo.getPage(),
                modelVo.getInputData(), WeChatEnum.SubscribeMessage_MiniprogramState.DEVELOPER, null);

        if("0".equals(retMap.get("errcode").toString())){
            log.info("===>微信小程序-订阅消息_推送成功！");
            return ResultModel.ok();
        }else{
            String errStr = "===>微信小程序-订阅消息_推送失败！errcode:"+retMap.get("errcode").toString()+"\t"+retMap.get("errmsg").toString();
            log.info(errStr);
            return ResultModel.error(ResultStatus.SERVER_ERROR, errStr);
        }
    }

}
